
// 只有请求结果返回 200 的时候，才会resolve，否则reject
const url = "https://admin.sms.skadoosh.cn/api/"
const request = (api, params = {}, method = "GET", header = {}) => {
  return new Promise(function(resolve, reject) {
    if (!header["content-type"]) {
      // header["content-type"] = "application/x-www-form-urlencoded"
      header["content-type"] = "application/json;charset=utf-8"
    }
    
    let token = wx.getStorageSync('token') || ''
    if (token && !header['Authorization']) {
      header['Authorization'] = 'Bearer ' + token
      header['token'] = token
      // + token
    } else if (header['Authorization']) {
      header['Authorization'] = header['Authorization']
    }

    wx.request({
      url: url + api,
      data: params,
      method: method,
      header: header,
      success: function(res) {
        if (res.statusCode == 200) {
          let ret = res.data
          console.log(ret)
          console.log(ret.code == 200)
          if (ret.code == 200) {
            console.log("进来了")
            resolve(ret.data);
          } else {
            wx.showToast({
              title: ret.message,
              icon: 'none'
            })
            reject(ret)
          }
        } else {
          wx.showToast({
            title: "服务器连接失败",
            icon: 'none'
          })
          reject(res);
        }
      },
      fail: function(err) {
        console.log(err,'错误')
        wx.showToast({
          title: "服务器连接失败",
          icon: 'none'
        })
        reject(err)
      }
    })
  });
}
module.exports = {
  request: request
}
